package com.moqianfan.mcuassistant.net;

import android.app.IntentService;
import android.content.Intent;

import com.moqianfan.mcuassistant.bean.ASMCourse;
import com.moqianfan.mcuassistant.bean.CCourse;
import com.moqianfan.mcuassistant.bean.CSource;
import com.moqianfan.mcuassistant.bean.McuCourse;
import com.moqianfan.mcuassistant.bean.McuOrder;
import com.moqianfan.mcuassistant.bean.McuSource;
import com.moqianfan.mcuassistant.comm.AppConfig;
import com.moqianfan.mcuassistant.database.ASMCourseDao;
import com.moqianfan.mcuassistant.database.CCourseDao;
import com.moqianfan.mcuassistant.database.CSourceDao;
import com.moqianfan.mcuassistant.database.McuCourseDao;
import com.moqianfan.mcuassistant.database.McuOrderDao;
import com.moqianfan.mcuassistant.database.McuSourceDao;
import com.moqianfan.mcuassistant.utils.LogUtil;

import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

/**
 * Created by Administrator on 2017/6/14.
 * 获取数据 service
 */

public class GetDataService extends IntentService {
    private static String TAG = "GetDataService";
    private McuCourseDao mcuCourseDao;
    private CSourceDao sourseDao;
    private CCourseDao courseDao;
    private McuSourceDao mcuSourceDao;
    private ASMCourseDao asmCourseDao;
    private McuOrderDao mcuOrderDao;
    private AppConfig appConfig;

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     */
    public GetDataService() {
        super("GetDataService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        appConfig = AppConfig.getAppConfig();
        mcuCourseDao = appConfig.getDaoSession().getMcuCourseDao();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (mcuCourseDao.loadAll().size() < 119) {
            getMcuCourse();
        } else {
            LogUtil.w(TAG, "MCU教程已缓存");
        }
        sourseDao = appConfig.getDaoSession().getCSourceDao();
        if (sourseDao.loadAll().size() < 200) {
            getCSourse();
        } else {
            LogUtil.w(TAG, "C函数库已缓存");
        }
        courseDao = appConfig.getDaoSession().getCCourseDao();
        if (courseDao.loadAll().size() < 260) {
            getCCourse();
        } else {
            LogUtil.w(TAG, "C教程数据库已缓存");
        }
        mcuSourceDao = appConfig.getDaoSession().getMcuSourceDao();
        if (mcuSourceDao.loadAll().size() < 3890)
            getMcuSourse();

        asmCourseDao = appConfig.getDaoSession().getASMCourseDao();
        if (asmCourseDao.loadAll().size() < 181) {
            getASMCourse();
        }

        mcuOrderDao = appConfig.getDaoSession().getMcuOrderDao();
        if (mcuOrderDao.loadAll().size() <= 0) {
            try {
                String sql = readMcuOrder(getAssets().open("McuOrder.json"));
                JSONArray array = new JSONArray(sql);
                int length = array.length();
                LogUtil.d(TAG, "汇编数据 " + length);
                for (int i = 0; i < length; i++) {
                    LogUtil.d(TAG, "汇编数据" + array.get(i).toString());
                    mcuOrderDao.insert(new McuOrder(array.getJSONArray(i).getInt(0),
                            array.getJSONArray(i).getString(1),
                            array.getJSONArray(i).getString(2),
                            array.getJSONArray(i).getString(3),
                            array.getJSONArray(i).getInt(4),
                            array.getJSONArray(i).getInt(5),
                            array.getJSONArray(i).getString(6)
                    ));
                }

            } catch (Exception e) {
                LogUtil.d(TAG, "汇编数据异常=" + e.toString());
                e.printStackTrace();
            }
        } else {
            LogUtil.w(TAG, "汇编指令数据库已缓存");
        }
    }


    /**
     * 获取单片机基础教学数据
     */
    private void getMcuCourse() {
        BmobQuery<McuCourse> query = new BmobQuery<>();
        query.order("head");
        query.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ONLY);
        query.setLimit(100);
        query.setSkip(mcuCourseDao.loadAll().size());
        query.findObjects(new FindListener<McuCourse>() {
            @Override
            public void done(List<McuCourse> list, BmobException e) {
                if (null == e) {
                    for (McuCourse item : list) {
                        LogUtil.w(TAG, item.toString());
                    }
                    mcuCourseDao.insertInTx(list);
                    if (mcuCourseDao.loadAll().size() < 119)
                        getMcuCourse();
                } else {
                    LogUtil.w(TAG, e.toString());
                }
            }
        });
    }

    private void getCSourse() {
        BmobQuery<CSource> query = new BmobQuery<>();
        query.order("head");
        query.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ONLY);
        query.setLimit(100);
        query.setSkip(sourseDao.loadAll().size());
        query.findObjects(new FindListener<CSource>() {
            @Override
            public void done(List<CSource> list, BmobException e) {
                if (null == e) {
                    for (CSource item : list) {
                        LogUtil.w(TAG, item.toString());
                    }
                    sourseDao.insertInTx(list);
                    if (sourseDao.loadAll().size() < 200)
                        getCSourse();
                } else {
                    LogUtil.w(TAG, e.toString());
                }
            }
        });
    }

    private void getCCourse() {
        BmobQuery<CCourse> query = new BmobQuery<>();
        query.order("title");
        query.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ONLY);
        query.setLimit(100);
        query.setSkip(courseDao.loadAll().size());
        query.findObjects(new FindListener<CCourse>() {
            @Override
            public void done(List<CCourse> list, BmobException e) {
                if (null == e) {
                    for (CCourse item : list) {
                        LogUtil.w(TAG, item.toString());
                    }
                    courseDao.insertInTx(list);
                    if (courseDao.loadAll().size() < 260)
                        getCCourse();
                } else {
                    LogUtil.w(TAG, e.toString());
                }
            }
        });
    }

    private void getMcuSourse() {
        BmobQuery<McuSource> query = new BmobQuery<>();
        query.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ONLY);
        query.setSkip(mcuSourceDao.loadAll().size());
        query.setLimit(100);
        query.findObjects(new FindListener<McuSource>() {
            @Override
            public void done(List<McuSource> list, BmobException e) {
                if (null == e) {
                    for (McuSource item : list) {
                        LogUtil.w(TAG, item.toString());
                    }
                    mcuSourceDao.insertInTx(list);
                    if (mcuSourceDao.loadAll().size() < 3890)
                        getMcuSourse();
                } else {
                    LogUtil.w(TAG, e.toString());
                }
            }
        });
    }

    private void getASMCourse() {
        BmobQuery<ASMCourse> query = new BmobQuery<>();
        query.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ONLY);
        query.setSkip(asmCourseDao.loadAll().size());
        query.setLimit(100);
        query.order("head");
        query.findObjects(new FindListener<ASMCourse>() {
            @Override
            public void done(List<ASMCourse> list, BmobException e) {
                if (null == e) {
                    for (ASMCourse item : list) {
                        LogUtil.w(TAG, item.toString());
                    }
                    asmCourseDao.insertInTx(list);
                    if (asmCourseDao.loadAll().size() < 181)
                        getASMCourse();
                } else {
                    LogUtil.w(TAG, e.toString());
                }
            }
        });
    }

    /**
     * 按行读取txt
     *
     * @param is 文件流
     * @return 读取到的文件内容
     * @throws Exception 异常
     */
    private String readMcuOrder(InputStream is) throws Exception {
        InputStreamReader reader = new InputStreamReader(is);
        BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuilder buffer = new StringBuilder("");
        String str;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
            buffer.append("\n");
        }
        return buffer.toString();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.w(TAG, "onDestroy");
    }
}
